<template>
  <div  class="sc-tree">
  <a-input-search
      v-if="normalTreeData.length"
      :allowClear="true"
      :placeholder="$i18n('template.category.search.input.tip')"
      class="search-btn"
      style="width: 190px;margin:0px 14px;"
      v-model="searchValue"
      @change="onSearchValueChange"
      @search="searchChange"
  />
  <a-tree
    class="tree-container"
    v-if="treeData.length"
    v-model="checkedKeys"
    :treeData="loadTreeData"
    :selectedKeys="selectedKeys"
    :defaultExpandedKeys="expandedKeys"
    @select="onSelect">
    <template slot-scope="text" slot="doc">
      <div :title="text.label" >{{ text.label }}</div> 
    </template>
    <template slot-scope="text" slot="folder">
      <div :title="text.label">
        <i class="sc-tree-select-icon xicon-wenjianjia-xian" />
        <span>{{ text.label }}</span>
      </div> 
    </template>
  </a-tree>
</div>
</template>
<script>
  const SELECT_TEMPLATE = 'template';

  export default {
    props: {
      treeData: {
        type: Object,
        default: () => {}
      },
      normalTreeData: {
        type: Array,
        default: () => []
      },
      data: {
        type: Object,
        default: () => {}
      },
      mapData:{
        type: Object,
        default: () => {}
      },
      type: {
        type: String
      },
    },
    data() {
      return {
        searchValue: '',
        checkedKeys: [],
        selectedKeys:[],
      };
    },
    watch: {
      data(newVal) {
        console.log('监听value变化')
        if (this.type === SELECT_TEMPLATE) {
          if (newVal.indexOf('C_') !== -1) {
            this.selectedKeys =[newVal.split('_')[1]] ;
            this.checkedKeys =[newVal.split('_')[1]] ;
            return;
          }
          this.selectedKeys = [newVal];
          this.checkedKeys =[newVal]
        }
      }
    },
    created() {
    },
    mounted() {
    },
    computed: {
      expandedKeys(){
        const getKeys = (arr) => {
          let keys = []
          arr.forEach(item => {
            if (item?.children?.length) {
              keys.push(item.key)
              keys = keys.concat(getKeys(item.children))
            }
          })
          return keys
        }
        return  this.treeData?.length ? getKeys(this.treeData) : []
      },
      loadTreeData(){//treeData字段改变了若是搜索模板名称有值需要过滤出对应的数据
        if(this.treeData && this.treeData.length > 0 && this.searchValue){
          return this.filterSearchTreeData(this.searchValue,this.treeData);
        }
        return this.treeData;
      }
    },
    methods: {
      valueChange(targetKeys) {
        let targetObj = this.mapData[targetKeys[0]];
        let retValue = {};
        if (this.type === SELECT_TEMPLATE) {
          if (!targetObj) {
            return retValue;
          }
          retValue.text = targetObj.name;
          if (targetObj.type === 'template') {
            retValue.templatePanel = targetObj.id;
            return retValue;
          }
          if (targetObj.unionIds && targetObj.unionIds.indexOf(',') > -1) {
            retValue.templatePanel = targetObj.unionIds
              .split(',')
              .map((id) => 'C_' + id)
              .join(',');
            return retValue;
          }
          retValue.templatePanel = 'C_' + targetObj.id;
          return retValue;
        }
      },
      onSelect(value) {
        console.log('onSelect',value);
        if(value.length == 0) return;
        const targetKeys = [value];
        this.selectedKeys = targetKeys;
        this.checkedKeys = targetKeys;
        //var formatValue = value[0].split('_').length>1?[value[0].split('_')[1]]:targetKeys;
        const params = this.valueChange(targetKeys);
        this.$emit('triggerValueChange', params,value);
      },
      onCheck(checkedKeys) {
        this.checkedKeys = checkedKeys;
      },
      onSearchValueChange(e){
        this.searchValue = e.target.value;
      },
      searchChange(e) {
          this.searchValue = e;
          var searchValue =  this.searchValue.trim();
          if(!searchValue){
            return this.$emit("searchTreeNode",JSON.parse(JSON.stringify(this.normalTreeData)));;
          }
          var  treeData = JSON.parse(JSON.stringify(this.normalTreeData))
          console.log('this.searchValue',this.searchValue)
          this.$emit("searchTreeNode",this.filterSearchTreeData(searchValue,treeData));
        },
      filterSearchTreeData(searchValue,treeData){
        const filterTreeData = (nodes) => {
            return nodes.filter((node) => {
                if(node.type == "template" && node.label.toLowerCase().indexOf(searchValue)>-1){
                  return true;
                }
                if(node.children){
                  node.children = filterTreeData(node.children);
                  return node.children.length>0
                }
                return false;
            });
          };
          return filterTreeData(treeData);
      },
      clean(){
        this.searchValue = '';
        // this.checkedKeys = [];
        // this.selectedKeys = [];
      }
    }
  };
</script>
<style lang="scss">
  .sc-tree{
    display: flex;
    flex-direction: column;
    flex-grow:1;
    overflow: auto;
  }
  .sc-tree-select-icon {
    font-size: 14px;
    color: #595959;
    margin-right: 3px;
  }
  .search-btn{
    position:sticky;
    top:0;
    z-index: 10px;
    width:190px;
    height: 30px;
    margin:0px 14px;
  }
  .tree-container{
    max-height: calc(100% - 30px);
    overflow: auto;
    flex:1;
    padding: 0px 14px;
  }
  .ant-tree {
    padding-top: 4px;
  }
  .ant-tree li .ant-tree-node-content-wrapper {
    min-width: calc(100% - 20px);
    width: auto;
    padding: 3px 4px 3px 0;
    line-height:20px;
    height: 26px;
    color:#333;
  }
  .ant-tree li .ant-tree-node-content-wrapper-normal {
    min-width: 100%;
    margin-left: 18px;
  }
  .ant-tree li span.ant-tree-switcher.ant-tree-switcher-noop {
    display: none;
  }
  .ant-tree li {
    margin: 0;
    padding: 2px 0px;
  }
  .ant-tree li ul {
    margin-bottom: 1px;
    padding: 0 0 0 22px;
  }
  
  .ant-tree>li:first-child{
    padding-top:0px;
  }
  .ant-tree-child-tree>li:first-child{
    padding-top: 4px;
  }
  .ant-tree li .ant-tree-node-content-wrapper:hover {
    background-color: #F5F5F5;
    background-color: var(--theme-brand0, #f5f5f5);
  }
  .ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected,
  .ant-tree li .ant-tree-node-selected .sc-tree-select-icon {
    background: var(--theme-brand1, #E6F6FF) !important;
    color: var(--theme-brand5, #1890ff) !important;
  }
::-webkit-scrollbar{
    width: 4px;
    height: 4px;
  }
</style>
